<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>推送</title>
</head>
<body>
  <button id="btn">发送</button>
  <script>
    function urlBase64ToUint8Array(base64String) {
      const padding = '='.repeat((4 - base64String.length % 4) % 4);
      const base64 = (base64String + padding)
        .replace(/-/g, '+')
        .replace(/_/g, '/');
    
      const rawData = window.atob(base64);
      const outputArray = new Uint8Array(rawData.length);
    
      for (let i = 0; i < rawData.length; ++i) {
        outputArray[i] = rawData.charCodeAt(i);
      }
      return outputArray;
    }
    navigator.serviceWorker.register('./sw-push.js').then(function(registration) {
      return registration.pushManager.getSubscription().then(async function(subscription) {
        // 注册部分
        if (subscription) {
          return subscription;
        }
        const response = await fetch('./vapidPublicKey');
        const vapidPublicKey = await response.text();
        const convertedVapidKey = urlBase64ToUint8Array(vapidPublicKey);
        return registration.pushManager.subscribe({
          userVisibleOnly: true,
          applicationServerKey: convertedVapidKey,
        })
      });
    }).then(function(subscription) {
      // 订阅部分
      fetch('./register', {
        method: 'POST',
        headers: {
          'Content-type': 'application/json',
        },
        body: JSON.stringify({
          subscription: subscription,
        }),
      });

      const btn = document.getElementById('btn');
      btn.onclick = function() {
        fetch('./sendNotification', {
          method: 'post',
          headers: {
            'Content-type': 'application/json',
          },
          body: JSON.stringify({
            subscription: subscription,
            payload: '随便一个吧',
            delay: 1,
            ttl: 10,
          })
        });
      };
    });
  </script>
</body>
</html>